package org.voyager.service.wx.web.wx;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.voyager.service.wx.common.result.JsonResult;
import org.voyager.service.wx.config.WxMpConfiguration;
import org.voyager.service.wx.model.WxRequestBO;

/**
 * @author Edward
 */
@RestController
@RequestMapping("/wx/user")
public class WxOauthController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    StringRedisTemplate redisTemplate;

    @PostMapping(value = "/getUserInfo")
    //public JsonResult getUserInfo(@RequestJson(value = "code") String code) {
    public JsonResult getUserInfo(@RequestBody WxRequestBO bo) {
        JsonResult jsonResult = JsonResult.ok();
        WxMpService mpService = WxMpConfiguration.getMpService();

        try {
            WxMpOAuth2AccessToken accessToken = mpService.oauth2getAccessToken(bo.getCode());
            WxMpUser user = mpService.oauth2getUserInfo(accessToken, null);
            jsonResult.put("openid", accessToken.getOpenId())
                    .put("user", user);
//            .put("accessToken", accessToken.getAccessToken())
//                    .put("refreshToken", accessToken.getRefreshToken())
        } catch (WxErrorException e) {
            e.printStackTrace();
            logger.warn("查询微信用户出错：code => {}, msg => {}", e.getError().getErrorCode(), e.getError().getErrorMsg());
            return JsonResult.error().setCode(e.getError().getErrorCode()).setMessage(e.getError().getErrorMsg());
        }

        return jsonResult;
    }

    @PostMapping("/getUserInfoByRefreshAccessToken")
    public JsonResult oauth2refreshAccessToken(@RequestParam String refreshAccessToken) {
        JsonResult jsonResult = JsonResult.ok();
        WxMpService mpService = WxMpConfiguration.getMpService();

        try {
            WxMpOAuth2AccessToken accessToken = mpService.oauth2refreshAccessToken(refreshAccessToken);
            WxMpUser user = mpService.oauth2getUserInfo(accessToken, null);
            jsonResult.put("accessToken", accessToken.getAccessToken())
                    .put("refreshToken", accessToken.getRefreshToken())
                    .put("openid", accessToken.getOpenId())
                    .put("user", user);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return JsonResult.error();
        }

        return jsonResult;
    }
}
